﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common;
namespace IntelligentFiles.HcCommon
{
    /// <summary>
    /// 智能柜控制板
    /// </summary>WW
    class LockControl
    {
       static SerialPort kzb = new SerialPort();
        /// <summary>
        /// 开锁
        /// </summary>
        /// <param name="deviceId">板号</param>
        /// <param name="deviceDoor">锁号</param>
        /// <param name="COM"></param>
        public static void OpenLocker(int deviceId, int deviceDoor)
        {
            try
            {
                OpenCom();
                CommonApi.writeLog("开锁，板号:" + deviceId + ",锁号:" + deviceDoor);
                sendMsg(deviceId, deviceDoor);
            }
            catch(Exception ex)
            {
                CommonApi.writeLog("开锁异常,"+ex.ToString());
            }
        }
        /// <summary>
        /// 端口打开
        /// </summary>
        public static bool OpenCom( )
        {
            if (!kzb.IsOpen)
            {
                kzb.PortName = ComParam.lockCom;
                kzb.BaudRate = 9600;//串口波特率，固定值
                kzb.Parity = System.IO.Ports.Parity.None;
                kzb.StopBits = System.IO.Ports.StopBits.One;
                kzb.DataBits = 8;//数据位
                kzb.Handshake = System.IO.Ports.Handshake.None;
                kzb.Encoding = Encoding.ASCII;//编码方式
                kzb.Open();
            }
            return kzb.IsOpen;
        }
        /// <summary>
        /// 命令 8A
        /// </summary>
        /// <param name="deviceId"></param>
        /// <param name="deviceDoor"></param>
        private static void sendMsg(int deviceId, int deviceDoor)
        {
            byte[] byteRecive = new byte[5];
            byteRecive[0] = 0x8A;
            byteRecive[1] = Convert.ToByte(deviceId);
            byteRecive[2] = Convert.ToByte(deviceDoor);
            byteRecive[3] = 0x11;
            byteRecive[4] = Get_CheckXor(byteRecive);
            kzb.Write(byteRecive, 0, byteRecive.Length);
        }

        /// <summary>
        /// BCC和校验代码 奇校验
        /// </summary>
        /// <param name="data">需要校验的数据包</param>
        /// <returns></returns>
        public static byte Get_CheckXor(byte[] data)
        {
            byte CheckCode = 0;
            int len = data.Length;
            for (int i = 0; i < len; i++)
            {
                CheckCode ^= data[i];
            }
            return CheckCode;
        }
    }
}
